import java.io.IOException;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class UVMapper extends Mapper<LongWritable, Text, Text, NullWritable> {

    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, NullWritable>.Context context) throws IOException, InterruptedException {
        try {
            String line = value.toString();
            // $remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"
            // e.g.:
            // 191.100.10.133 - - [16/Jun/2021:01:14:55 +0800] "GET / HTTP/1.1" 200 4833 "-" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36" "-"
            Pattern pattern = Pattern.compile("(.*?)\\s+-\\s+(.*?)\\s+\\[(.*?)\\]\\s+\"(.*?)\"\\s+(\\d+)\\s+(\\d+)\\s+\"(.*?)\"\\s+\"(.*?)\"\\s+\"(.*?)\"");
            Matcher matcher = pattern.matcher(line);
            if (matcher.find()) {
                String ip = matcher.group(1);
                Date date = nginxTimeAsDate(matcher.group(3));
                // String uri = ParsedNginxRequest.parseRequest(matcher.group(4)).uri;
                context.write(new Text(new SimpleDateFormat("yyyy-MM-dd hh:00:00").format(date) + "\t" + ip), NullWritable.get());
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return;
        }
    }

    private Date nginxTimeAsDate(String str) throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM/yyyy:hh:mm:ss Z", Locale.ENGLISH);
        Date date = formatter.parse(str);
        return date;
    }
}